<?php

namespace app\index\controller;
use \think\Request;
use app\common\model\Cars as CarsModel;
use app\common\request\Curl;
use app\common\request\Command;
use think\Log;
use think\Db;
use app\common\enums\ResultEnum;
use app\common\utils\ResultVOUtil;
use app\common\request\ClientLai;
use app\common\model\CarsInfo;


class Message extends Base
{
    public function index()
    {
        
        $request = Request::instance();
        
        if($request->isAjax()){
            $post = $request->post();
            
            if( !empty($post['datemin']) && !empty($post['datemax']) ){
                $where['create_time'] = ['between time',[$post['datemin'],$post['datemax']]];
                
            }
            if ( empty($post['datemin']) && !empty($post['datemax']) ){
                $where['create_time'] = ['<= time',$post['datemax']];
                
                
            }
            if ( !empty($post['datemin']) && empty($post['datemax']) ) {
                $where['create_time'] = ['> time',$post['datemin']];
                
            }
            if ( !empty($post['search_inpute']) ) {
                $where['car_sn|car_unique_id|cardcode|equipment_id|sim_id'] = ['like','%'.$post['search_inpute'].'%'];
                
            }
            if ( !empty($post['supplier_no']) ) {
                $where['supplier_no'] = $post['supplier_no'];
                
            }
            if ( !empty($post['sim_card']) ) {
                $where['sim_card'] = $post['sim_card'];
                    
            }
            
            if( empty($where) ){
                $where = '1=1';
            }
            $model= CarsModel::with('carsInfo')
            ->where($where)
            ->order('car_id', 'desc')
            ->field('car_id,car_sn,car_unique_id,equipment_id,sim_id,cardcode,create_time,supplier_no,sim_card')
            ->paginate($post['length'],false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$post['start']/$post['length'] +1 ,
            ]);
              
            if(count($model)>=1){
                foreach ($model as $key => $value) {
                    $res['data'][] = $value;
                }
                $res['recordsTotal'] = $res['recordsFiltered'] = $model->total();
   
            }else{
                $res['data'] = '';
                $res['recordsTotal'] = $res['recordsFiltered'] =0;
                
            }
            
            return $res;
               
        }else{
                
            $model = CarsModel::count(); 
            $this->assign('number',$model);
            return $this->fetch();
        }
    }
    
    public function send(){
        $request = Request::instance();
        if($request->isAjax()){
            $param = $request->post();
            $data['recNum'] = $param['phone_number'];
            $data['templateParam'] = $param['content'];
            $data['templateType'] = 2;
            $data['time'] = time();
            $url = 'http://120.79.71.83:81/send_sms';
            
            $content = Command::response($data,$url);

            if(!empty($content)){
                $arr = json_decode($content,true);
                if($arr['code'] == 0){
                    return [
                        'result'=>0,
                        'msg'=>'发送成功'
                    ];

                }else{
                    return [
                        'result'=>1,
                        'msg'=>$arr['msg']
                    ];
               }
            }
            
        }else{
            return $this->fetch();
        }
        
    }

    public function smsup(){
        $request = Request::instance();
        if($request->isAjax()){
            $post = $request->post();
            $data['page'] = $post['start']/$post['length'] +1;
            $data['size'] = $post['length'];
            $data['search'] = '';
            $url = "http://120.79.71.83:81/show_smsup";
            $content = Command::response($data,$url);
            if(!empty($content)){
                $arr = json_decode($content,true);
                if(count($arr)>=1){
                    foreach ($arr['data']['data'] as $key => $value) {
                        
                        $dataum['data'][] = $value;
                    
                    }
                    $dataum['recordsTotal'] = $dataum['recordsFiltered'] = $arr['data']['total'];
   
                }else{
                    $dataum['data'] = '';
                    $dataum['recordsTotal'] = $dataum['recordsFiltered'] =0;
                    
                }
                
                return $dataum;
            }
            

        }else{
            return $this->fetch();
        }
    }

    public function smsdown(){
        $request = Request::instance();
        if($request->isAjax()){
            $post = $request->post();
            $data['page'] = $post['start']/$post['length'] +1;
            $data['size'] = $post['length'];
            $data['search'] = '';
            $url = "http://120.79.71.83:81/show_send";
            $content = Command::response($data,$url);
            
            if(!empty($content)){
                $arr = json_decode($content,true);
                if(count($arr)>=1){
                    foreach ($arr['data']['data'] as $key => $value) {
                        
                        $dataum['data'][] = $value;
                    
                    }
                    $dataum['recordsTotal'] = $dataum['recordsFiltered'] = $arr['data']['total'];
   
                }else{
                    $dataum['data'] = '';
                    $dataum['recordsTotal'] = $dataum['recordsFiltered'] =0;
                    
                }
                
                return $dataum;
            }

        }else{
            return $this->fetch();
        }
    }

    public function details($sim_id){
        $data['iccid'] = $sim_id;
        $url = "http://120.79.71.83:81/card_status";
        $content = Command::response($data,$url);
        if(!empty($content)){
            $arr = json_decode($content,true);
            if($arr['code'] == 0){
                if(!empty($arr['data'])){
                    $dataum = $arr['data']['cardStatus'];
                    $model= CarsModel::where('sim_id',$sim_id)->field('car_sn,car_unique_id,equipment_id,sim_id,cardcode,supplier_no')->find();

                    $this->assign('cars',$model);
                    $this->assign('data',$dataum);
                    return $this->fetch();

                }else{
                    $dataum = null;
                    $model = null;

                    $this->assign('data',$dataum);
                    return $this->fetch('error');
                }

            }else{
                $dataum = $arr['msg'];
                $model = null;

                $this->assign('data',$dataum);
                return $this->fetch('error');
            }
        }
        

    }

    public function operate($cardcode){
        $request = Request::instance();
        if($request->isAjax()){
            $param = $request->param();
            $data['recNum'] = $param['cardcode'];
            $data['templateParam'] = $param['action'];
            $data['templateType'] = 2;
            $data['time'] = time();
            $url = 'http://120.79.71.83:81/send_sms';
            $content = Command::response($data,$url);
            if(!empty($content)){
                $arr = json_decode($content,true);
                if($arr['code'] == 0){
                    return [
                        'result'=>0,
                        'msg'=>'发送成功'
                    ];

                }else{
                    return [
                        'result'=>1,
                        'msg'=>$arr['msg']
                    ];
               }
            }
        }else{
            $model = new CarsModel();
            $cars = $model->where('cardcode',$cardcode)->field('supplier_no,cardcode')->find();
            $this->assign('cars',$cars);
            return $this->fetch();
        }
            
    }

    public function traffic($sim_id){
        $data['iccid'] = $sim_id;
        $url = "http://120.79.71.83:81/card_flow_info";
        $content = Command::response($data,$url);
        
        if(!empty($content)){
            $arr = json_decode($content,true);
            if($arr['code'] == 0){
                if(!empty($arr['data']['cardFlowInfos'])){

                    $dataum = $arr['data']['cardFlowInfos'][0];
                }else{
                    $dataum = null;
                }
                $this->assign('data',$dataum);
                return $this->fetch();
            }else{
                $dataum = $arr['msg'];
                $this->assign('data',$dataum);
                return $this->fetch('error');

            }
        }
    }

    public function package($sim_id){
        $data['iccid'] = $sim_id;
        $url = "http://120.79.71.83:81/iot_card_offer_dtl";
        $content = Command::response($data,$url);
        if(!empty($content)){
            $arr = json_decode($content,true);
            if($arr['code'] == 0){
                $dataum = $arr['data']['cardOfferDetail'];
                $this->assign('data',$dataum);
                return $this->fetch();
            }else{
                $dataum = $arr['msg'];
                $this->assign('data',$dataum);
                return $this->fetch('error');

            }
        }
    }
    /*
        *赛卡短信通道

    */

    public function dispach(){
        $request = Request::instance();
        if($request->isAjax()){
            $param = $request->post();
            $data['recNum'] = $param['phone_number'];
            $data['templateParam'] = $param['content'];
            $data['templateType'] = 2;
            $data['time'] = time();

            $url = 'http://120.79.71.83:81/gt_send_sms';
            
            $content = Command::response($data,$url);
            if(!empty($content)){
                $arr = json_decode($content,true);
                if($arr['code'] == 0){
                    return [
                        'result'=>0,
                        'msg'=>'发送成功'
                    ];

                }else{
                    return [
                        'result'=>1,
                        'msg'=>$arr['msg']
                    ];
               }
            }
            
        }else{
            return $this->fetch();
        }
    }

    /*
        *赛卡车辆控制
    */
    public function command($cardcode){
        $request = Request::instance();
        if($request->isAjax()){
            $param = $request->param();
            $data['recNum'] = $param['cardcode'];
            $data['templateParam'] = $param['action'];
            $data['templateType'] = 2;
            $data['time'] = time();
            $url = 'http://120.79.71.83:81/gt_send_sms';
            $content = Command::response($data,$url);
            if(!empty($content)){
                $arr = json_decode($content,true);
                if($arr['code'] == 0){
                    return [
                        'result'=>0,
                        'msg'=>'发送成功'
                    ];

                }else{
                    return [
                        'result'=>1,
                        'msg'=>$arr['msg']
                    ];
               }
            }
        }else{
            $model = new CarsModel();
            $cars = $model->where('cardcode',$cardcode)->field('supplier_no,cardcode')->find();
            $this->assign('cars',$cars);
            return $this->fetch();
        }
            
    }

    /**
        *赛卡套餐列表查询
    */
    public function information(){
        $request = Request::instance();
        $param = $request->param();
        $config = config('sk_api');

        $data['partnercode'] = $config['partnercode'];
        $data['servicecode'] = $config['servicecode'];
        $data['requesttime'] = date('YmdHis').'2500000001';
        $data['key'] = $param['cardcode'];
        $string = $config['password'].$data['requesttime'].$data['key'];
        $data['sign'] = md5(strtolower($string));
        $url = rtrim($config['url'],'/').'/M2MSearchInfo.ashx';
        $content = $this->demand($url,$data);
        if($content){
            $arr = json_decode($content,true);
            if($arr['status'] == 0000){
                $dataum = $arr['result'][0];
                $this->assign('data',$dataum);
                return $this->fetch();
            }else{
                $dataum = $arr['msg'];
                $this->assign('data',$dataum);
                return $this->fetch('error');
            }
        }
    }

    /**
        *赛卡查询卡状态
    */
    public function realTime($cardcode){
        $config = config('sk_api'); 
        $data['partnercode'] = $config['partnercode'];
        $data['servicecode'] = $config['servicecode'];
        $data['requesttime'] = date('YmdHis').'2500000001';
        $data['key'] = $cardcode;
        $data['status'] = 2;
        $string = $config['password'].$data['requesttime'].$data['key'].$data['status'];
        $data['sign'] = md5(strtolower($string));
        $url = rtrim($config['url'],'/').'/M2MSearchTermInfo.ashx';
        $content = $this->demand($url,$data);
        if($content){
            $arr = json_decode($content,true);
            if($arr['status'] == 0000){
                $dataum = $arr['result'][0];
                $this->assign('data',$dataum);
                return $this->fetch('real_time');
            }else{
                $dataum = $arr['msg'];
                $this->assign('data',$dataum);
                return $this->fetch('error');
            }
        }
    }

    /**
        *赛卡流量查询
    */
    public function flow($cardcode){
        $config = config('sk_api'); 
        $data['partnercode'] = $config['partnercode'];
        $data['servicecode'] = $config['servicecode'];
        $data['requesttime'] = date('YmdHis').'2500000001';
        $data['key'] = $cardcode;
        $string = $config['password'].$data['requesttime'].$data['key'];
        $data['sign'] = md5(strtolower($string));
        $url = rtrim($config['url'],'/').'/M2MSurplusFlow.ashx';
        $content = $this->demand($url,$data);
        if($content){
            $arr = json_decode($content,true);
            if($arr['status'] == 0000){
                $dataum = $arr['result'][0];
                $this->assign('data',$dataum);
                return $this->fetch();
            }else{
                $dataum = $arr['msg'];
                $this->assign('data',$dataum);
                return $this->fetch('error');
            }
        }
    }

    public function demand($url,$json){
        $url = $url; 
        $data = json_encode($json);
        $curl = curl_init($url);  // 初始化 cURL 会话
        curl_setopt($curl, CURLOPT_HEADER, false);  // 启用时会将头文件的信息作为数据流输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));  //设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100') 
        curl_setopt($curl, CURLOPT_POST, true);     //TRUE 时会发送 POST 请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  // 全部数据使用HTTP协议中的 "POST" 操作来发送。value必须是个数组
        $content = curl_exec($curl);  // 执行 cURL 会话 , 应该在初始化一个 cURL 会话并且全部的选项都被设置后被调用。 
        if(curl_errno($curl)){
            $content = [];
            Log::record(curl_errno($curl),'error');          
        }else{

            $info = curl_getinfo($curl);   // 获取一个cURL连接资源句柄的信息(获取最后一次传输的相关信息)
        
            if($info['http_code'] !== 200){

                $content = [];
                Log::record('对方服务器错误','error');
                
            }
        }
        
        curl_close($curl); // 关闭 cURL 会话
        return $content;
        
    }

    /*
        *切IOT
    */

    public function exchange($car_id){
        $CarsInfo = new CarsInfo;
        $model = new CarsModel;
        $cars = Db::name('cars')->where(['car_id'=>$car_id])->field('sim_card,band_status,car_unique_id,cardcode,equipment_id')->find();
        if($cars['band_status'] == 1){
            return ResultVOUtil::error(ResultEnum::ERROR['code'],'车辆未解绑');
        }else{
            $status = Db::name('terminal')->where(['equipment_id'=>$cars['equipment_id']])->value('status');
            if($status!==1){
                return ResultVOUtil::error(ResultEnum::ERROR['code'],'设备未注册');
            }else{
                $arr = $this->queryDetail($cars['equipment_id']);
                if($arr['data'][0]['success'] == true){
                    $data['recNum'] = $cars['cardcode'];
                    $data['templateType'] = 2;
                    $data['time'] = time();
                    $data['productKey'] = $arr['data'][0]['data']['productKey'];
                    $data['deviceSecret'] = $arr['data'][0]['data']['deviceSecret'];
                    $data['templateParam'] = '#836927,JCSZIOT:'.$data['productKey'].$data['deviceSecret'].'1883.iot-as-mqtt.cn-shanghai';
                           
                    if($cars['sim_card'] == 1376920004){
                        $url = 'http://120.79.71.83:81/send_sms';

                        $content = Command::response($data,$url);

                        if(!empty($content)){
                            $arr = json_decode($content,true);
                            if($arr['code'] == 0){
                                try{

                                    $CarsInfo->where(['car_unique_id' =>$cars['car_unique_id']])->update(['supplier_no' => 1376920003]);

                                }catch(\Exception $e){
                                    return ResultVOUtil::error(ResultEnum::ERROR['code'],$e->getMessage());
                                }

                                try{

                                    $model->where(['car_unique_id' => $cars['car_unique_id']])->update(['supplier_no' => 1376920003]);

                                }catch(\Exception $e){
                                    return ResultVOUtil::error(ResultEnum::ERROR['code'],$e->getMessage());
                                }

                                return ResultVOUtil::success('');

                            }else{
                                return ResultVOUtil::error(ResultEnum::ERROR['code'],$arr['msg']);
                           }
                        }
                        
                    }else if($cars['sim_card'] == 1376920005){
                        $url = 'http://120.79.71.83:81/gt_send_sms';

                        $content = Command::response($data,$url);

                        if(!empty($content)){
                            $arr = json_decode($content,true);
                            if($arr['code'] == 0){
                                try{

                                    $CarsInfo->where(['car_unique_id' => $cars['car_unique_id']])->update(['supplier_no' => 1376920003]);

                                }catch(\Exception $e){
                                    return ResultVOUtil::error(ResultEnum::ERROR['code'],$e->getMessage());
                                }

                                try{

                                    $model->where(['car_unique_id' => $cars['car_unique_id']])->update(['supplier_no' => 1376920003]);

                                }catch(\Exception $e){
                                    return ResultVOUtil::error(ResultEnum::ERROR['code'],$e->getMessage());
                                }

                                return ResultVOUtil::success('');
                            }else{
                                return ResultVOUtil::error(ResultEnum::ERROR['code'],$arr['msg']);
                           }
                        }
                    }

                }
            }
        }

    }

    public function queryDetail($param){
        $config = config('local_iot');
        $obj = new ClientLai($config['user_name'],$config['password']);

        $data['device_name'] = $param;
        $res = $obj->request_post(rtrim($config['url'],'/').'/device/queryDeviceDetail',$data);
        if($res){
            $arr = json_decode($res,true);
            
        }else{
            $arr = null;
        }
        
        return $arr; 
        
    }

}

